package com.chengyu.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Set;

/**
 * @author Miracle Luna
 * @date 2022/4/30
 */
public class JsonUtil {

    public static void convert(Object obj) {
        if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) obj;
            for (Object json : jsonArray) {
                convert(json);
            }
        } else if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            Set<String> keySet = json.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            for (String key : keyArray) {
                Object value = json.get(key);
                String[] keyStrs = key.split("_");
                if (keyStrs.length > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < keyStrs.length; i++) {
                        String keyStr = keyStrs[i];
                        if (!keyStr.isEmpty()) {
                            if (i == 0) {
                                sb.append(keyStr);
                            } else {
                                int c = keyStr.charAt(0);
                                if (c >= 97 && c <= 122) {
                                    int v = c - 32;
                                    sb.append((char) v);
                                    if (keyStr.length() > 1) {
                                        sb.append(keyStr.substring(1));
                                    }
                                } else {
                                    sb.append(keyStr);
                                }
                            }
                        }
                    }
                    json.remove(key);
                    json.put(sb.toString(), value);
                }
                convert(value);
            }
        }
    }

    /**
     * 将json字符串中的key名称中包含下划线的字段，转成驼峰命名格式
     *
     * @param str String格式的JSON串
     * @return 转换后的对象（可能是JSONObject或JSONArray）
     */
    public static Object convertUnderlineToCamelCase(String str) {
        Object obj = JSON.parse(str);
        convert(obj);
        return obj;
    }

    public static void main(String[] args) {
        String json = "{\"namespaces\":[{\"self_auth\":{\"user_id\":\"050b12577f00269a1fcfc01f65239697\",\"auth\":7,\"user_name\":\"user\"},\"auth\":7,\"name\":\"group\",\"creator_name\":\"username\",\"id\":1343008,\"others_auths\":[{\"user_id\":\"06d89c3b6d800f2d1f28c01f0d882285\",\"auth\":1,\"user_name\":\"user_01\"},{\"user_id\":\"050b12577f00269a1fcfc01f65239697\",\"auth\":7,\"user_name\":\"user\"}]}]}";
        System.out.println(convertUnderlineToCamelCase(json));
    }
}
